import type { TabPaneName } from 'element-plus'

import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router'
import { useTabListStore } from '@/stores'

export function useTabList() {
  const route = useRoute()
  const router = useRouter()
  const tabListStore = useTabListStore()
  const activeTab = ref<string>(route.path) // 当前激活的标签 '/goods/list'
  const tabList = computed(() => tabListStore.tabList)

  const removeTab = (targetName: TabPaneName) => {
    const index_delete = tabList.value.findIndex((item) => item.path === targetName)
    const index_active = tabList.value.findIndex((item) => item.path === activeTab.value)
    index_delete !== -1 && tabListStore.removeTabIndex(index_delete)
    if (index_delete == index_active) {
      activeTab.value = tabList.value[index_active]?.path || tabList.value[index_active - 1].path
      router.push(activeTab.value)
    }
  }
  // 切换tabs页时，同步激活菜单项
  const changeTab = (tabName: string) => {
    activeTab.value = tabName
    router.push(tabName)
  }
  const handleCommand = (command: string) => {
    if (command === 'closeOther') {
      tabListStore.removeOtherTabs(activeTab.value as string)
    }
    if (command === 'closeAll') {
      activeTab.value = '/'
      tabListStore.removeAllTabs()
    }
  }
  // 增加并激活新tabs页
  onBeforeRouteUpdate((to, from) => {
    activeTab.value = to.path
    tabListStore.addTab({ title: to.meta.title as string, path: to.path })
  })

  return {
    activeTab,
    tabList,
    changeTab,
    removeTab,
    handleCommand
  }
}
